#!/usr/bin/env node
var path = require('path');
var fs = require('fs');
var _ = require('lodash');
var proxyMiddleware = require('http-proxy-middleware');
// var browserSync = require('browser-sync');
var express = require("express");
var app = express();
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
//var webpackDevMiddleware = require("webpack-dev-middleware");
var webpackConfig = require('./make.webpack.config.js');
var program = require('commander');
var pkg = require("./package.json");

program
	.version('0.0.1')
	.option('-d, --dev', '开发环境')
	.option('-b, --build', '测试编译环境')
	//.option('-b, --build [type]','编译环境[test]','test')
	.parse(process.argv);
if (program.dev) {
	dev();
}

if (program.build) {
	build(program.build,"prod");
}
if (program.run) {
	run();
}

function run(argument) {
	var runConfig = webpackConfig({ dev: false });
	var bundler = webpack(runConfig);
	browserSync({
		port: 8888,
		server: {
			baseDir: runConfig.buidDir,
			server: true
		},

		// no need to watch '*.js' here, webpack will take care of it for us,
		// including full page reloads if HMR won't work
		files: [
			runConfig.buidDir + '/*.html'
		]
	});
}
function dev(argument) {
	function getIPAdress() {
		let interfaces = require('os').networkInterfaces();
		for (var devName in interfaces) {
			var iface = interfaces[devName];
			for (var i = 0; i < iface.length; i++) {
				let alias = iface[i];
				if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
					return alias.address
				}
			}
		}
	}
	const IP = getIPAdress();

	var devConfig = webpackConfig({ dev: true,env:"dev" });
	for (var key in devConfig.entry) {
		devConfig.entry[key].unshift('webpack-hot-middleware/client?reload=true')
	}
	var bundler = webpack(devConfig);
	var devMiddleware = webpackDevMiddleware(bundler, {
		// IMPORTANT: dev middleware can't access config, so we should
		// provide publicPath by ourselves
		publicPath: devConfig.output.publicPath,
		//noInfo: true,
		// pretty colored output
		stats: { colors: true }
		// for other settings see
		// http://webpack.github.io/docs/webpack-dev-middleware.html
	});
	var proxy1 = proxyMiddleware(pkg.proxy, {
		target: "http://"+IP+":8080"
	});
    let port = 3333;
    // app.use(proxy1);
    app.use(devMiddleware);
    app.use(webpackHotMiddleware(bundler));
    let listenStr = `listen at http://localhost:${port},......`;
    console.log(`listen at http://localhost:${port},......`);                      
    app.listen(port);
}

function build(argument,env) {
	var config = webpackConfig({ dev: false,env:env });
	var compiler = webpack(config, function (err, stats) {
		if (err) {
			console.log('编译出错了！');
		} else {
			console.log(stats.toString({ colors: true }));
		}
	});
	compiler.apply(new webpack.ProgressPlugin(function handler(percentage, msg) {
		console.log((percentage * 100) + '%', msg);
	}));
}
